package com.rbac.web.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.web.db.RoleDAO;
import com.rbac.web.db.RoleDO;
import com.rbac.web.model.PageResult;
import com.rbac.web.model.PageV0;
import com.rbac.web.model.Role;
import com.rbac.web.service.IRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * @author gengaoliu
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements IRoleService {
  private final RoleDAO dao;

  @Override
  public void insert(Role role) {
    dao.insert(RoleDO.from(role));
  }

  @Override
  public void update(Role role) {
    dao.updateById(RoleDO.from(role));
  }

  @Override
  public void deleteById(Integer id) {
    dao.deleteById(id);
  }

  @Override
  public Optional<Role> selectById(Integer id) {
    return Optional.of(dao.selectById(id).to());
  }

  @Override
  public PageResult<Role> findAll(String name, PageV0 pageV0) {
    IPage<RoleDO> page =
        dao.selectPage(
            Page.of(pageV0.getPage(), pageV0.getSize()),
            Wrappers.<RoleDO>lambdaQuery().like(StringUtils.hasText(name), RoleDO::getName, name));
    List<Role> roleList = page.getRecords().stream().map(RoleDO::to).toList();
    return PageResult.of(page.getCurrent(), page.getSize(), page.getTotal(), roleList);
  }
}
